package handler

import (
	"fmt"
	"web_framework/config"
	"web_framework/model"
	"web_framework/pkg/constvar"
	"web_framework/pkg/e"
	"web_framework/service"
	"web_framework/storage"
)

//保持心跳
type HeartHandle struct {
}

func (heartHandle HeartHandle) handleMsg(data model.Request) (result model.Response) {

	//检查参数是否为空
	if len(data.Data.Sn) == 0 {
		return ReturnErr(data.Mid, constvar.DownloadHeartResponeMtype, "sn参数必传")
	}
	//更新上下行速度
	speedCacheKey := constvar.RedisRouterSpeedPrefix + data.Data.Sn
	hashData := map[string]interface{}{
		"upspeed":   data.Data.UpSpeed,
		"downspeed": data.Data.DownSpeed,
	}
	storage.RedisHSet(speedCacheKey, hashData, 10)

	return model.Response{
		Mid:    data.Mid,
		Mtype:  constvar.DownloadHeartResponeMtype,
		Info:   "心跳正常",
		Status: constvar.StatusOk,
	}
}

//登录身份验证
type LoginHandle struct {
}

func (loginHandle LoginHandle) handleMsg(data model.Request) (result model.Response) {

	if data.Mtype == constvar.DownloadInitRequestMtype {
		//检查参数是否为空
		if data.Data.Sn == "" || data.Data.Mac == "" {
			return ReturnErr(data.Mid, constvar.DownloadInitResponeMtype, "sn/mac参数必传")
		}
		//验证SN码的合法性
		validErr := service.ValidateSN(data.Data.Sn, data.Data.Mac)
		if validErr != nil {
			fmt.Printf("%s", validErr)
			return ReturnErr(data.Mid, constvar.DownloadInitResponeMtype, validErr.Error())
		}
		//签名验证
		paramsSign := []string{string(data.Time), string(data.Mid), data.Data.Sn, data.Data.Mac}
		errSign, _ := e.CheckSign(data.Sign, paramsSign)
		if errSign != nil {
			return ReturnErr(data.Mid, constvar.DownloadInitResponeMtype, "签名错误")
		}
		//查询初始化配置
		downConfig, err := storage.GetConfig(config.C.DB.DB, 1)
		if err != nil {
			return
		}
		return model.Response{
			Mid:    data.Mid,
			Mtype:  constvar.DownloadInitResponeMtype,
			Info:   "登录成功",
			Status: constvar.StatusOk,
			Data: model.Data{
				HbInterval:       downConfig.HbInterval,
				ScanReturnPage:   downConfig.ScanReturnPage,
				SearchReturnPage: downConfig.SearchReturnPage,
				LimitSpeed: model.LimitSpeed{
					UpSpeed:   downConfig.UpSpeed,
					DownSpeed: downConfig.DownSpeed,
				},
				TasksVer: 101,
				Tasks: []model.Task{
					model.Task{
						TaskID: 1,
						URL:    "https://pan.baidu.com/s/1S20Tpjqq8iWVNDz1iInCSw",
					},
				},
			},
		}
	}
	return ReturnErr(data.Mid, constvar.DownloadInitResponeMtype, "登录失败")
}
